using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TerritoryGame.Application.Interfaces;
using TerritoryGame.Application.Dtos;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Entities.App;

namespace TerritoryGame.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class GameController : ControllerBase
    {
        private readonly IAppGameService _gameService;

        public GameController(IAppGameService gameService)
        {
            _gameService = gameService;
        }

        /// <summary>
        /// 记录绘画动作
        /// </summary>
        [HttpPost("paint-action")]
        public async Task<IActionResult> RecordPaintAction([FromBody] PaintActionRequest request)
        {
            try
            {
                var userId = User.FindFirst("sub")?.Value ?? 
                            User.FindFirst("user_id")?.Value ?? 
                            User.FindFirst("uid")?.Value;
                
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized(ApiResult.Failed(401, "用户未认证"));
                }

                // 创建PaintAction对象
                var paintAction = new PaintAction
                {
                    RoomId = Guid.Parse(request.RoomId),
                    PlayerId = Guid.Parse(userId),
                    X = request.X,
                    Y = request.Y,
                    Color = request.Color,
                    Tool = request.Tool,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };

                var result = await _gameService.RecordPaintActionAsync(paintAction);
                
                return Ok(ApiResult.Success("绘画动作记录成功", new
                {
                    id = result.Id,
                    roomId = result.RoomId,
                    playerId = result.PlayerId,
                    x = result.X,
                    y = result.Y,
                    color = result.Color,
                    tool = result.Tool,
                    timestamp = result.Timestamp
                }));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"记录绘画动作失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取房间画布数据
        /// </summary>
        [HttpGet("canvas/{roomId}")]
        [AllowAnonymous]
        public async Task<IActionResult> GetCanvasData(string roomId)
        {
            try
            {
                // 这里应该返回画布的实际数据
                // 暂时返回一个模拟的画布状态
                var canvasData = new
                {
                    roomId = roomId,
                    width = 800,
                    height = 600,
                    backgroundColor = "#FFFFFF",
                    lastUpdated = DateTime.UtcNow,
                    message = "画布数据获取成功"
                };

                return Ok(ApiResult.Success("获取画布数据成功", canvasData));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取画布数据失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 重置画布
        /// </summary>
        [HttpPost("canvas/{roomId}/reset")]
        public async Task<IActionResult> ResetCanvas(string roomId)
        {
            try
            {
                var userId = User.FindFirst("sub")?.Value ?? 
                            User.FindFirst("user_id")?.Value ?? 
                            User.FindFirst("uid")?.Value;
                
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized(ApiResult.Failed(401, "用户未认证"));
                }

                // 这里应该实现画布重置逻辑
                // 暂时返回成功消息
                var result = new
                {
                    roomId = roomId,
                    resetBy = userId,
                    resetTime = DateTime.UtcNow,
                    message = "画布重置成功"
                };

                return Ok(ApiResult.Success("画布重置成功", result));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"重置画布失败: {ex.Message}"));
            }
        }
    }

    /// <summary>
    /// 绘画动作请求模型
    /// </summary>
    public class PaintActionRequest
    {
        public string RoomId { get; set; } = string.Empty;
        public int X { get; set; }
        public int Y { get; set; }
        public string Color { get; set; } = string.Empty;
        public string Tool { get; set; } = string.Empty;
    }
}
